<template>
  <div>
    <el-form :model="params" ref="ruleForm" label-width="110px" size="small">
      <el-form-item label="模板名称" prop="name"
                    :rules="[{ required: true, message: '模板名称未填', trigger: 'change'}]">
        <el-input type="input" style="width: 300px;" placeholder="请输入模板名称" v-model="params.name" />
      </el-form-item>
      <el-form-item label="计费方式">
        <el-radio-group v-model="params.billingmethod">
          <el-radio :label="1">按件计算</el-radio>
          <el-radio :label="2">按重计算</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="配送区域">
        <div class="flex-row table-wrap table-head">
          <div class="left">可配送区域</div>
          <div class="right flex-row">
            <div class="item">操作</div>
            <div class="item" v-if="params.billingmethod === 1">首件(个)</div>
            <div class="item" v-if="params.billingmethod === 2">首重(Kg)</div>
            <div class="item">运费(元)</div>
            <div class="item" v-if="params.billingmethod === 1">续件(个)</div>
            <div class="item" v-if="params.billingmethod === 2">续重(Kg)</div>
            <div class="item">续费(元)</div>
          </div>
        </div>
        <div class="flex table-wrap table-item" v-for="(item,index) in params.distributionAreas" :key="index">
          <div class="left">{{item.province|filterCity(item.city,dataList)}}</div>
          <div class="right flex-row">
            <el-form-item label="" class="item">
              <el-button type="text" @click="setArea(index)">修改</el-button>
              <el-button type="text" @click="deleteArea(index)">删除</el-button>
            </el-form-item>
            <el-form-item class="item" v-if="params.billingmethod === 1"
                          :prop="'distributionAreas.'+index+ '.firstpiece'"
                          :rules="[{ required: true, message: '首件未填', trigger: 'change' }]" >
              <el-input-number style="width: 110px" :min="0" :precision="0" v-model="item.firstpiece" />
            </el-form-item>
            <el-form-item class="item" v-if="params.billingmethod === 2"
                          :prop="'distributionAreas.'+index+ '.firstweight'"
                          :rules="[{ required: true, message: '首重未填', trigger: 'change' }]">
              <el-input-number style="width: 110px" :min="0" :precision="1" v-model="item.firstweight" />
            </el-form-item>
            <el-form-item class="item"
                          :prop="'distributionAreas.'+index+ '.freight'"
                          :rules="[{ required: true, message: '运费未填', trigger: 'change' }]">
              <el-input-number style="width: 110px" :min="0" :precision="2" v-model="item.freight" />
            </el-form-item>
            <el-form-item class="item" v-if="params.billingmethod === 1"
                          :prop="'distributionAreas.'+index+ '.continuedpiece'"
                          :rules="[{ required: true, message: '续件未填', trigger: 'change' }]" >
              <el-input-number style="width: 110px" :min="0" :precision="0" v-model="item.continuedpiece" />
            </el-form-item>
            <el-form-item class="item" v-if="params.billingmethod === 2"
                          :prop="'distributionAreas.'+index+ '.continuedweight'"
                          :rules="[{ required: true, message: '续重未填', trigger: 'change' }]" >
              <el-input-number style="width: 110px" :min="0" :precision="1" v-model="item.continuedweight" />
            </el-form-item>
            <el-form-item class="item"
                          :prop="'distributionAreas.'+index+ '.continuedfreight'"
                          :rules="[{ required: true, message: '续费未填', trigger: 'change' }]">
              <el-input-number style="width: 110px" :min="0" :precision="2" v-model="item.continuedfreight" />
            </el-form-item>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="openArea()">指定可配送区域和运费</el-button>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button><el-button>取消</el-button>
      </el-form-item>
    </el-form>

    <div class="dialog" v-show="showSelectArea" @click="showSelectArea = false">
      <div class="inner" style="width:740px" @click.stop>
        <div class="title flex">
          <div class="name">选择配送区域</div>
          <i class="el-icon-close" @click="showSelectArea = false"></i>
        </div>
        <div class="center">
          <div class="select-item flex" v-for="(item, index) in itemArea" :key="item.name">
            <div class="area">
              <label class="checkbox-wrap" @click="chooseArea(index)"
                     :class="{'checkbox-checked': showAreaChecked(index),
                    'checkbox-indeterminate': showAreaInput(index) && !showAreaChecked(index) }">
                <span class="checkbox">
                  <span class="checkbox-inner"></span>
                </span>
                <span>{{item.name}}</span>
              </label>
            </div>
            <div class="prov flex">
              <div class="pro-list" v-for="list in item.province" :key="list.areaCode">
                <label class="checkbox-wrap"
                       :class="{'checkbox-checked': curProvince.indexOf(list.areaCode) > -1,
                       'checkbox-indeterminate': curCity.map(i => i.slice(0,2)).indexOf(list.areaCode.slice(0,2)) > -1 && curProvince.indexOf(list.areaCode) === -1 }">
                  <span class="checkbox">
                    <span class="checkbox-inner"></span>
                    <input type="checkbox" :value="list.areaCode" v-model="curProvince" @change="choseProvince(list.areaCode)">
                  </span>
                  <span>{{list.areaName}}
                    <i style="color: red;" v-if="(curCity.filter(i =>i.slice(0,2) == list.areaCode.slice(0,2))).length">
                      ({{(curCity.filter(i =>i.slice(0,2) == list.areaCode.slice(0,2))).length}})
                    </i>
                    <i class="el-icon-arrow-down"></i>
                  </span>
                </label>
                <div class="city-list" v-if="list.child.length">
                  <div class="popper__arrow"></div>
                  <div class="city-item" v-for="mi in list.child" :key="mi.areaCode">
                    <label class="checkbox-wrap" :class="{'checkbox-checked': curCity.indexOf(mi.areaCode) > -1 }">
                      <span class="checkbox">
                        <span class="checkbox-inner"></span>
                        <input type="checkbox" :value="mi.areaCode" v-model="curCity" @change="choseCity(list.areaCode, mi.areaCode)" >
                      </span>
                      <span>{{mi.areaName}}</span>
                    </label>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="button flex-row">
            <span class="total">已选{{curCity.length}}个区域</span>
            <el-button type="primary" plain :disabled="curCity.length === 0" @click="submit()">提交</el-button>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>
<script>
  import { areaSelect, freightTemplateSave, freightTemplateUpdate } from '@/api/sc_other'
  export default {
    data() {
      return {
        showSelectArea: false, // 选择城市
        params: {
          name: '',
          billingmethod: 1, // 1:按件数 2：按重量
          businessId: null, // 商家id
          distributionAreas: [] // 配送区域
        },
        itemArea: [
          { name: '东北', key: ['21', '22', '23'], province: [] },
          { name: '华东', key: ['31', '32', '33', '34', '36'], province: [] },
          { name: '华中', key: ['41', '42', '43'], province: [] },
          { name: '华南', key: ['35', '44', '45', '46'], province: [] },
          { name: '华北', key: ['11', '12', '13', '14', '15', '37'], province: [] },
          { name: '西北', key: ['61', '62', '63', '64', '65'], province: [] },
          { name: '西南', key: ['50', '51', '52', '53', '54'], province: [] },
          { name: '港澳台', key: ['71', '81', '82'], province: [] },
        ],
        dataList: [], // 三级联动数据
        curProvince: [], // 临时数据选中的省份
        curCity: [], // 临时数据选中的城市
        editIndex: null // 临时数据 操作的索引
      }
    },
    filters: {
      filterCity(p, c, l) { // 展示选中的区域
        if (l && l.length && c && c.length) {
          let str = []
          let citys = c
          if (p && p.length) {
            for (let i = 0; i < p.length; i++) {
              const pIndex = l.findIndex(e => e.areaCode === p[i])
              str.push(l[pIndex].areaName)
              citys = citys.filter(e => e.slice(0,2) !== p[i].slice(0,2))
            }
          }
          if (citys.length) {
            const allCity = l.reduce((acr, cval) => acr.concat(cval.child),[])
            for (let i = 0; i< citys.length; i++) {
              const cIndex = allCity.findIndex(e => e.areaCode === citys[i])
              str.push(allCity[cIndex].areaName)
            }
          }
          return str.join('、')
        } else {
           return ''
        }
      }
    },
    methods: {
      getAreaSelect() { // 获取所有的数据
        areaSelect().then(res => {
          if (res.success) {
            this.dataList = res.data
            for (let i = 0; i< this.itemArea.length; i++) {
              if (res.data.length) {
                for (let j = 0; j < res.data.length; j++) {
                  if (this.itemArea[i].key.indexOf(res.data[j].areaCode.slice(0,2)) > -1) {
                    this.itemArea[i].province.push(res.data[j])
                  }
                }
              }
            }
          }
        })
      },
      openArea() { // 新建区域
        this.editIndex = null
        this.curCity = []
        this.curProvince = []
        this.showSelectArea = true
      },
      setArea(index) { // 修改
        this.editIndex = index
        this.curCity = [...this.params.distributionAreas[index].city]
        this.curProvince = [...this.params.distributionAreas[index].province]
        this.showSelectArea = true
      },
      deleteArea(index) { // 删除
        this.params.distributionAreas.splice(index, 1)
      },
      submit() { // 确认修改区域
        if (this.editIndex !== null) {
          this.params.distributionAreas[this.editIndex].province = [...this.curProvince]
          this.params.distributionAreas[this.editIndex].city = [...this.curCity]
        } else {
          this.params.distributionAreas.push({
            templateid: null, firstpiece: '1', freight: '0', continuedpiece: '1', continuedfreight: '0',
            firstweight: '0', continuedweight: '0', province: [...this.curProvince], city: [...this.curCity] })
        }
        this.showSelectArea = false
      },
      submitForm(formName) { //提交数据
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = { ...this.params }
            if (this.$route.query.cid) {
              params.id = this.$route.query.cid
              freightTemplateUpdate(params).then(res => {
                if (res.success) {
                  
                }
              })
            } else {
              freightTemplateSave(params).then(res => {
                if (res.cuccess) {

                }
              })
            }
          }
        })
      },
      showAreaInput(index) { // 监听 是否含有当前区域的省份、城市、县区
        const key = this.itemArea[index].key.map(i => i.slice(0,2))
        return this.curCity.findIndex(i => key.indexOf(i.slice(0,2))>-1)> -1
      },
      showAreaChecked(index) { // 监听区域是全选
        const key = this.itemArea[index].key
        return key.every(e=> this.curProvince.findIndex(i => i.slice(0,2) === e) > -1)
      },
      choseProvince(val) { // 选择省
        const s = this.curProvince.indexOf(val)
        const p = this.dataList.findIndex(e => e.areaCode == val)
        const citys = this.dataList[p].child.map(code => code.areaCode)
        if (s > -1) {
          const arr = this.curCity.concat(citys)
          this.curCity = [...new Set(arr)]
        } else {
          this.curCity = this.curCity.filter(e => val.slice(0,2) !== e.slice(0,2))
        }
      },
      choseCity(val) { // 选择省份
        const p = this.dataList.findIndex(e => e.areaCode == val)
        const citys = this.dataList[p].child.map(code => code.areaCode)
        const isFull = citys.every(i => this.curCity.findIndex(s => s === i) > -1)
        const pIndex = this.curProvince.indexOf(val)
        if (isFull) {
          if (pIndex === -1) this.curProvince.push(val)
        } else {
          if (pIndex > -1) this.curProvince.splice(pIndex, 1)
        }
      },
      chooseArea(index) { // 点击 区域筛选
        const key = this.itemArea[index].key
        const isCheackAll = key.every(i => this.curProvince.findIndex(s => s.slice(0,2) === i) > -1) // 全选了
        if (isCheackAll) {
          this.curCity = this.curCity.filter(i => key.findIndex(s => s === i.slice(0,2)) === -1)
          this.curProvince = this.curProvince.filter(i => key.findIndex(s => s === i.slice(0,2)) === -1)
        } else {
          const keys = key.map(i => i + '0000')
          this.curProvince = [...new Set(keys.concat(this.curProvince))]
          let arr = []
          for (let i = 0; i < keys.length; i++) {
            const code = keys[i]
            const pIndex = this.dataList.findIndex(e => e.areaCode == code)
            arr = arr.concat(this.dataList[pIndex].child.map(code => code.areaCode))
          }
          this.curCity = [...new Set(arr.concat(this.curCity))]
        }
      }
    },
    mounted() {
      this.getAreaSelect()
      this.params.businessId = this.$route.query.id
    }
  }
</script>

<style lang="scss" scoped>
  @import "./scss/sc_other.scss";
</style>
